package top.lyjwn.ajui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import top.lyjwn.ajui.R;
import top.lyjwn.ajui.widget.banner.BannerItem;
import top.lyjwn.ajui.widget.banner.BannerView;
import top.lyjwn.ajui.widget.image.NetImageView;

/**
 * 轮播图适配器
 *
 * @author luoyujie
 */
public class BannerSingleAdapter extends RecyclerView.Adapter<BannerSingleAdapter.BannerItemHolder> implements BannerAdapter {

    private List<BannerItem> urls;
    private Context context;
    private BannerView.OnClickItemListener listener;

    public BannerSingleAdapter(Context context, BannerView.OnClickItemListener listener) {
        this.urls = new ArrayList<>();
        this.context = context;
        this.listener = listener;
    }

    @Override
    public BannerItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.widget_banner_1image_item, parent, false);
        return new BannerItemHolder(view);
    }

    @Override
    public void onBindViewHolder(BannerItemHolder holder, final int position) {
        if (urls.size()==0){
            return;
        }
        holder.imageView.load(urls.get(position % urls.size()).getImgUrl());
        if (listener == null) {
            holder.imageView.preview(urls.get(position % urls.size()).getImgUrl());
        } else {
            holder.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onItemClick(urls.get(position % urls.size()), position % urls.size());
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return Integer.MAX_VALUE;
    }

    public class BannerItemHolder extends RecyclerView.ViewHolder {
        private NetImageView imageView;

        public BannerItemHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.item_image);
            imageView.getImageView().setScaleType(ImageView.ScaleType.FIT_XY);
        }
    }


    public void refresh(List<? extends BannerItem> urls) {

        if (this.urls!=null){
            for (int i = 0; i < this.urls.size(); i++) {
                removeItem();
            }
        }


        for (int i = 0; i < urls.size(); i++) {
            this.urls.add(urls.get(i));
            //添加动画
            notifyItemInserted(i);
        }
    }

    //  删除数据
    public void removeItem() {
        urls.clear();
        //删除动画
        notifyDataSetChanged();
    }

    @Override
    public List<BannerItem> getItems() {
        return urls;
    }


}
